package top.huashengshu.geekbang;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.huashengshu.common.HttpDownloadUtils;
import top.huashengshu.geekbang.http.GeekBangHttpUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GeekBangUtils {
    /**
     * 没有必要自定义线程池因为这只是一个小工具
     * 第一个线程池是用于下载资源的
     * 第二个线程池用于合并音频和视频文件为一个可播放的mp4文件
     */
    private static ExecutorService downloadThreadPool = Executors.newFixedThreadPool(4);//适当的调整，建议5个以内，太大了容易被封ip

    public static void main(String[] args) throws Exception {
//        GeekBangHttpUtils.downloadFile("https://static001.geekbang.org/resource/audio/f5/6d/f5869e083ecb4c59597ce8eb8964fa6d.mp3","E:/1.mp3");
        List<String> list = Arrays.asList(
                "https://b.geekbang.org/member/course/detail/160463",
                "https://b.geekbang.org/member/course/detail/6354"
        );
        for (String url : list) {
            String articleId = GeekBangHttpUtils.getArticleId(url);
            downloadAllArticleAudio(articleId);
        }


    }

    private static void downloadAllArticleAudio(String articleId) throws Exception {
        JSONObject courseDetail = GeekBangHttpUtils.getCourseDetail(articleId);
        System.out.println("课程信息：");
        System.out.println(courseDetail);
        JSONObject data = courseDetail.getJSONObject("data");
        Long pid = data.getLong("pid");
        String directName = data.getString("column_title");
        System.out.println("pid=" + pid);
        JSONObject articles = GeekBangHttpUtils.getArticles(pid);
        System.out.println("所有文章：");
        // System.out.println(articles);
        JSONArray list = articles.getJSONObject("data").getJSONArray("list");
        HashMap<String, String> map = new HashMap<>();
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            JSONObject tempData = list.getJSONObject(i);
            String category = tempData.getString("title");
            JSONArray article_list = tempData.getJSONArray("article_list");
            for (int j = 0; j < article_list.size(); j++) {
                JSONObject article = article_list.getJSONObject(j);
                // 拿到文章的标题和音频信息，准备下载
                JSONObject detail = article.getJSONObject("article");
                String title = detail.getString("title");
                String num = String.format("%03d", count);
                String fileName = num + ". " + category + " - " + title + ".mp3";
                JSONObject audio = article.getJSONObject("audio");
                String download_url = audio.getString("download_url");
                map.put(fileName.replace("|", "-").replace("/", "-"), download_url);
                count++;
            }
        }
        String finalDriveName = "E:/";
        map.forEach((fileName, downloadUrl) -> {
            String audioSavePath = finalDriveName + directName + "/" + fileName;
            CompletableFuture<Boolean> vflag = CompletableFuture.supplyAsync(() -> {
                try {
                    return GeekBangHttpUtils.downloadFile(downloadUrl, audioSavePath);//下载图像文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }, downloadThreadPool);
        });
    }
}
